package calificaciones;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import sistemas.sam.R;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class SeleccionarCuatrimestre extends Activity implements OnItemSelectedListener,OnClickListener {

	InputStream is = null;
	StringBuilder sb = null;
	JSONArray jArray=null;
	String result = null;
	String []materias;
	String []materias_id;
	TextView text;
	String idC;
	Button consulta;
	link l;
	Intent i;
	private ConectarSam mAuthTask = null;
	public List<String> Lcuatri =new ArrayList<String>(); 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_seleccionar_cuatrimestre);
		
	
		
		text=(TextView) findViewById(R.id.texto);
		consulta=(Button) findViewById(R.id.consultar);
		consulta.setOnClickListener(this);
		cuatrimestre c=new cuatrimestre();
		Lcuatri.addAll(c.cuatri());
		ArrayAdapter<String> adaptado2 = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, Lcuatri);
		Spinner sp = (Spinner) findViewById(R.id.cuatrimestre);
		adaptado2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp.setAdapter(adaptado2);
	//	adaptado2.notifyDataSetChanged();
		sp.setOnItemSelectedListener(this);
	}
	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int location,
			long arg3) {
	
		
		if(arg0.getId()==R.id.cuatrimestre){
			idC=""+(location+1);
			Toast.makeText(getApplicationContext(), ""+idC, Toast.LENGTH_LONG).show();
		}
		
	}
	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onClick(View v) {
		if(v.getId()==R.id.consultar){
	mAuthTask=new ConectarSam();
				mAuthTask.execute((Void)null);
			 i=new Intent(this,PruebaCalificacion.class);
			
		
			//startActivity(i);
			
		}
		
	}

	
	private void abrirDashboard() {
	i.putExtra("materia",materias);
		i.putExtra("materiaID",materias_id);
		startActivity(i);
	}
	
	public class ConectarSam extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			// http post
	
			
			
			try {
				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost("http://192.168.1.68/SAM/materiasCuatrimestre?id="+idC);
				Log.v("log_tag", "http://192.168.1.68/SAM/materiasCuatrimestre?id=5");
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
			} catch (Exception e) {
				Log.e("Error URL-Cuatri ", " "
						+ e.toString());
			}
			try {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");

				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				result = sb.toString();
				Log.v("obtenido", result);
			} catch (Exception e) {
				Log.e("log_tag Selec cuatri",
						"Error convirtiendo datos recibidos en Cuatri " + e.toString());
			}
			try {
				jArray = new JSONArray(result);
				JSONObject json_data = null;
				materias =new String[jArray.length()]; 
				materias_id=new String[jArray.length()];
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					materias[i]= json_data.getString("nombre");	
				materias_id[i]=json_data.getString("materiaID");	
					Log.d("msg", "paso  "+materias[i]);
					Log.d("mate_id", "paso  "+materias_id[i]);
				}
			} catch (JSONException e1) {
				Log.e("JSON ERR", e1.getMessage());
			} catch (ParseException e1) {
				e1.printStackTrace();
			}
			return true;
		}
		@Override
		protected void onPostExecute(final Boolean success) {
			mAuthTask = null;
			//showProgress(false);
			Log.v("login_resultado", success.toString());
			if (success) {
				
				abrirDashboard();

			} else {
				
			}
		}

		@Override
		protected void onCancelled() {
			mAuthTask = null;
			//showProgress(false);
		}
	}
}
